import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Modal,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { SelectGardenParams } from '../data';

const { Option } = Select;

const search = {
  pareaCode: '',
  name: '',
  type: '',
  propertyId: '',
  pageIndex: 1,
  pageSize: 10,
};

interface SelectGardenProps extends FormComponentProps {
  dispatch?: Dispatch;
  INITINFO?: any;
  gardenInfo?: any;
  VisibleGarden: boolean;
  ChangeGarden: (visibleGarden: boolean) => void;
  SelectGarden: (selectGarden: { id: number, name: string }) => void;
}

interface SelectGardenState {
  searchVales: SelectGardenParams;
}

@connect(({
  cabinetManagementAdd: { gardenInfo },
  common: { INITINFO },
}: any) => ({ gardenInfo, INITINFO }))

class SelectGardenElem extends Component<SelectGardenProps, SelectGardenState> {
  state = {
    searchVales: search,
  }

  columns = [
    {
      title: '小区',
      dataIndex: 'name',
      render: (val: string) => {
        let value = '';
        if (val && val.length > 8) value = `${val.substring(0, 8)}...`;
        else value = val;
        return <span title={val}>{value}</span>;
      },
    },
    {
      title: '物业公司',
      dataIndex: 'propertyName',
      render: (val: string) => {
        let value = '';
        if (val && val.length > 8) value = `${val.substring(0, 8)}...`;
        else value = val;
        return <span title={val}>{value}</span>;
      },
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      render: (val: string) => {
        let value = '';
        if (val && val.length > 18) value = `${val.substring(0, 18)}...`;
        else value = val;
        return <span title={val}>{value}</span>;
      },
    },
    {
      title: '场景',
      dataIndex: 'type',
      width: '12%',
      render: (val: number) => {
        const { INITINFO: { gardenType } } = this.props;
        let value = '';
        gardenType.map((item: any) => {
          if (item.mCode === val) value = item.codeName;
          return false;
        });
        return <span>{value}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (val: number, row: any) => (
        <span
          className="operLink"
          onClick={() => this.handleSelectGarden(row)}
        >选择
        </span>
      ),
    },
  ]

  componentDidMount() {
    const { searchVales } = this.state;
    this.fetchAction('fetchGarden', searchVales);
    this.fetchAction('common/fetchGardenType');
    this.fetchAction('common/fetchAllProperty');
    this.fetchAction('common/fetchAreaList');
  }

  handleSelectGarden = (row: any) => {
    const { SelectGarden } = this.props;
    SelectGarden({ id: row.id, name: row.name });
    this.handleCancel();
  }

  handleCancel = () => {
    const { ChangeGarden, form: { resetFields } } = this.props;
    this.setState({
      searchVales: search,
    }, () => {
      resetFields();
      ChangeGarden(false);
      this.fetchAction('fetchGarden', search);
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (!errors) {
        const params = {
          ...search,
          ...values,
          pareaCode: values.pareaCode ? values.pareaCode : '',
          type: values.type ? values.type : '',
          pageIndex: 1,
          pageSize: 10,
        };
        this.setState({
          searchVales: params,
        }, () => this.fetchAction('fetchGarden', params));
      }
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchVales } = this.state;
    const params = {
      ...searchVales,
      pageIndex,
      pageSize,
    };
    this.setState({
      searchVales: params,
    }, () => this.fetchAction('fetchGarden', params));
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch }: any = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cabinetManagementAdd/${typeName}`;
    dispatch({ type, payload });
  }

  render() {
    const { searchVales: { pageIndex, pageSize } } = this.state;
    const {
      form: { getFieldDecorator },
      VisibleGarden,
      gardenInfo,
      INITINFO: { gardenType, allPropertyList, areaList },
    } = this.props;

    const dataSource = gardenInfo ? gardenInfo.list : [];
    const pagination: object = {
      total: gardenInfo ? gardenInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${gardenInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Modal
        title="小区(学校)"
        visible={VisibleGarden}
        width={800}
        destroyOnClose
        footer={null}
        onCancel={this.handleCancel}
      >
        <Form className="tableListForm marginB20" onSubmit={this.handleSearch}>
          <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
            <Col md={8} sm={24}>
              <Form.Item label="小区" colon={false}>
                {getFieldDecorator('name')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col md={8} sm={24}>
              <Form.Item label="物业公司" colon={false}>
                {getFieldDecorator('propertyId')(
                  <Select
                    showSearch
                    placeholder="请选择"
                    filterOption={(input: any, option: any) => (
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    )}
                  >
                    {allPropertyList.map((item: any) => (
                      <Option value={item.id} key={item.id}>{item.name}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col md={8} sm={24}>
              <Form.Item label="场景" colon={false}>
                {getFieldDecorator('type', { initialValue: 0 })(
                  <Select>
                    <Option value={0}>全部</Option>
                    {gardenType.map((item: any) => (
                      <Option value={item.mCode} key={item.mCode}>{item.codeName}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
            <Col md={8} sm={24}>
              <Form.Item label="省份" colon={false}>
                {getFieldDecorator('pareaCode', { initialValue: 0 })(
                  <Select>
                    <Option value={0}>全部</Option>
                    {areaList.map((item: any) => (
                      <Option value={item.code} key={item.code}>{item.name}</Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col md={8} sm={24}> </Col>
            <Col md={8} sm={24}>
              <div className="flexFeView">
                <Button
                  type="primary"
                  size="small"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
        <Table
          rowKey="id"
          className="statementTable"
          columns={this.columns}
          dataSource={dataSource}
          pagination={pagination}
        />
      </Modal>
    );
  }
}

export default Form.create<SelectGardenProps>()(SelectGardenElem);
